package com.ssvendas.servlet;

import java.io.IOException;
import java.io.InputStream;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import com.ssvendas.fachadas.remote.QueryProdutoRemote;
import com.ssvendas.modelo.Produto;

@WebServlet(name = "midia", urlPatterns = { "/midia" })
public class Midia extends HttpServlet {

        private static final long serialVersionUID = -7748738652983031614L;

        @EJB
        private QueryProdutoRemote queryP;
        
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                        throws ServletException, IOException {
        	
        	if(req.getParameter("idProduto")==null){
        		resp.setContentType("img/jpg");
	            resp.getOutputStream().write(getFotoDefault());
        	}else{
        	
	        	Produto p = queryP.getProduto(req.getParameter("idProduto"));
	        		        	
				if(p.getFoto() == null){
					resp.setContentType("img/jpg");
		            resp.getOutputStream().write(getFotoDefault());
				}else{
		            resp.setContentType("img/jpg");
		            resp.getOutputStream().write(p.getFoto());
				}
        	}
        }
        
    	private byte[] getFotoDefault(){
    		ServletContext context = getServletContext();
			InputStream input = context.getResourceAsStream("/Images/indisponivel.jpg");
 		
 		    try {
 		        return IOUtils.toByteArray(input);
 		    }
 		    catch (IOException e) {
 		        e.printStackTrace();
 		        return null;
 		    }
 		}        
}